<template>
	<view style="padding-top: 10px;">
		<view class="bkk bl">
			<view>已选服务内容</view>
			<view class="bc">
				<i-icon size="24px" color="#008040" name="checkbox-circle-fill"></i-icon>
				<view v-html="serviceName||'<font color=#9d9d9d >[服务内容]</font>'"></view>
			</view>
		</view>
		<view class="bkk">
			<view class="b20">
				<view class="bc">
					<i-icon size="26px" color="#008040" name="user-3-fill"></i-icon>登记预约信息
				</view>
				<!-- <i-icon size="16px" color="#999" name="arrow-right-s-line"></i-icon> -->
			</view>
			<view class="">
				<view class="bc b20">
					<view class="r10">姓名</view>
					<input style="font-size: 18px;height: 50px;" type="text" v-model="userName" placeholder="请输入姓名" />
				</view>
				<view class="bc">
					<view class="r10">手机</view>
					<input style="font-size: 18px;height: 50px;" type="text" v-model="phone" placeholder="请输入手机号"
						maxlength="11" />
				</view>
			</view>
		</view>
		<view class="bkk">
			<view class="b20">
				<view class="bc">
					<i-icon size="26px" color="#008040" name="time-fill"></i-icon>服务收费价格
				</view>
				<!-- <i-icon size="16px" color="#999" name="arrow-right-s-line"></i-icon> -->
			</view>
			<view class="p-yyxx">
				￥{{serviceDate}}/次
			</view>
		</view>
		<view class="bkk">
			<view class="b20">
				<view class="bc">
					<i-icon size="26px" color="#008040" name="map-pin-3-fill"></i-icon>预约时间
				</view>
				<!-- <i-icon size="16px" color="#999" name="arrow-right-s-line"></i-icon> -->
			</view>
			<view class="p-yyxx">
				<view class="">全天</view>
			</view>
		</view>
		<view class="bkk">
			<view class="b20">
				<view class="bc">
					<i-icon size="26px" color="#008040" name="map-pin-3-fill"></i-icon>服务详细地点
				</view>
				<!-- <i-icon size="16px" color="#999" name="arrow-right-s-line"></i-icon> -->
			</view>
			<view class="p-yyxx">
				<view class="">{{serviceSite}}</view>
			</view>
		</view>
		<view style="margin: 10px;">
			<!-- <view class="bc" style="margin-bottom: 10px;font-size: 12px;">
				<i-icon size="20px" color="#008040" name="error-warning-line"></i-icon>您的爱心能量{{loveEnergy}}个，需要30个才可免费预约
			</view> -->
			<button @click="wxPay()">
				<i-icon size="16px" color="#FFF" name="radio-button-fill"></i-icon>支付
			</button>
		</view>
		<!-- 弹出成层 -->
		<uni-popup ref="popup" type="dialog" :animation="false">
			<view class="tcc">
				<view>
					第一次使用微信支付需微信授权
				</view>
				<navigator :url="wxPayUrl">授权</navigator>
			</view>
		</uni-popup>
		<view style="margin: 10px;font-size: 14px;" class="bc">
			<checkbox @click="agree=!agree" :checked="agree" /><text>阅读并同意《桂民社区服务站服务条款》</text>
		</view>
		<view style="height: 30px;"></view>
	</view>
</template>

<script>
	var wx = require('../../static/js/jweixin.js')
	export default {
		data() {
			return {
				userName: '',
				phone: '',
				serviceId: '',
				serviceName: '',
				serviceDate: '',
				serviceSite: '',
				price: '',
				loveEnergy: 30,
				times: [],
				agree: false,
				testAmount: 1, //测试金额
				wxAuthorizeUrl: '', //微信网页授权跳转路径
				wxPayUrl: '', //微信支付请求路径
				wxType: null, //是否为微信浏览器（1：微信内置浏览器，2：外部浏览器）
				wxReqData: {}, //微信支付请求参数
				redirectUrl: '', //微信授权重定向路径
				wxCode: '',
				openid: ''
			}
		},
		methods: {

			//关闭弹出层
			colse() {
				this.$refs.popup.close()
				//this.comfirm();
			},
			//打开弹出层
			wxPay() {
				//this.$refs.popup.open('top')
				let msg = null;
				if (!this.serviceName) {
					msg = "服务内容不能为空"
				} else if (!this.userName) {
					msg = "姓名不能为空"
				} else if (!this.phone) {
					msg = "手机号不能为空"
				} else if (!/\d{11}/.test(this.phone)) {
					msg = "手机号格式错误"
				} else if (!this.serviceSite) {
					msg = "活动地点不能为空"
				} else if (!this.agree) {
					msg = '请阅读并同意《桂民社区服务站服务条款》'
				}
				if (msg) {
					uni.showToast({
						title: msg,
						icon: 'none'
					})
					return
				}
				let _this = this;
				if (_this.wxType == 1) {
					let code = _this.wxCode
					console.log(code)
					uni.request({
						url: _this.baseURL + '/wxPay/get/openId?code=' + code,
						method: 'GET',
						success: (res) => {
							console.log(res)
							if (res.data.success == true) {
								_this.openid = res.data.data;
								console.log('此时的openid=>' + _this.openid)
								if (!_this.openid) {
									uni.showToast({
										title: '微信授权失败，openID为空',
										icon: 'error',
										duration: 3000
									})
									return;
								}
								_this.wxPayUrl = '/wxPay/JsApi'
								let trueAmount = _this.serviceDate * 100;
								_this.wxReqData = {
									amount: trueAmount, //金额 serviceDate
									commodity: _this.serviceName, //商品
									openId: _this.openid, //用户openid
									serviceId: _this.serviceId //商品id(用户后台校验价格)
								}
								console.log('此时的请求参数=>' + JSON.stringify(_this.wxReqData))
								_this.httpRequest({
									url: _this.wxPayUrl,
									method: 'POST',
									data: _this.wxReqData,
									fn(data) {
										console.log(data)
										//下单后得到签名后的参数，拉起微信支付
										wx.chooseWXPay({
											timestamp: data
											.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
											nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
											package: data
											.packages, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
											signType: data
											.signType, // 微信支付V3的传入RSA,微信支付V2的传入格式与V2统一下单的签名格式保持一致
											paySign: data.paySign, // 支付签名
											success: function(res) {
												// 支付成功后的回调函数
												console.log(res)
												_this.addOrder()
											},
											// 支付取消回调函数
											cancel: function(res) {
												Toast('用户取消支付~')
											},
											// 支付失败回调函数
											fail: function(res) {
												Toast('支付失败~')
											}
										})
									}
								})
							} else {
								uni.showToast({
									title: '微信授权失败，未获得openID',
									icon: 'error',
									duration: 3000
								})
								return;
							}
						},
						fail: (err) => {
							console.log(err)
							uni.showToast({
								title: '微信授权失败',
								icon: 'error',
								duration: 3000
							})
							return;
						}
					})
				} else if (_this.wxType == 2) {
					let trueAmount = _this.serviceDate * 100;
					_this.wxPayUrl = '/wxPay/H5'
					_this.wxReqData = {
						amount: trueAmount, //金额 serviceDate
						commodity: _this.serviceName, //商品
					}
					_this.httpRequest({
						url: _this.wxPayUrl,
						method: 'POST',
						data: _this.wxReqData,
						fn(data) {
							//微信重定向链接
							let parmas = "?serviceName=" + _this.serviceName +
								"&serviceDate=" + (_this.serviceDate || "[工作日]") +
								"&serviceSite=" + _this.serviceSite +
								"&type=" + _this.type +
								"&price=" + _this.price +
								"&unit=" + _this.unit
							let redUrl = 'http://h5.yunshuicha.com/#/pages/index/fw-yywc'
							//将重定向链接进行en编码
							let enUrl = encodeURIComponent(redUrl)
							//得到微信支付跳转链接
							//let wxUrl = data + '&redirect_url=' + enUrl
							let wxUrl = data;
							console.log(wxUrl)
							uni.setStorage({
								key: 'wxPayUrl',
								data: wxUrl,
								success: (res) => {
									console.log(res)
								}
							})
							uni.navigateTo({
								url: '../test/test2?url=' + wxUrl
							})
						}
					})
				}
			},
			addOrder() {
				let _this = this;
				_this.httpRequest({
					//添加预约
					url: '/service/appoint/add',
					method: 'POST',
					data: {
						userName: _this.userName,
						phone: _this.phone,
						serviceId: _this.serviceId,
						serviceName: _this.serviceName,
						serviceSite: _this.serviceSite,
						servicePrice: _this.serviceDate
					},
					fn(data) {
						uni.reLaunch({
							url: 'fw-yywc?serviceSite=' + _this.serviceSite + '&serviceName=' + _this
								.serviceName + '&type=支付预约' + '&price=' + _this.serviceDate + '&unit=元'
						})
					}
				})
			},
			//判断是否是微信内部浏览器
			is_weixin() {
				let _this = this;
				var ua = navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
					console.log('是微信内部浏览器')
					_this.wxType = 1;
					return true;
				} else {
					_this.wxType = 2;
					console.log('是外部浏览器')
					return false;
				}
			},
			//获取路径上的code参数
			getUrlParam(name) {
				var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
				let url = window.location.href.split('#')[0]
				let search = url.split('?')[1]
				if (search) {
					var r = search.substr(0).match(reg)
					if (r !== null)
						return unescape(r[2])
					return null
				} else
					return null
			},
			//初始化微信配置
			wxConfig() {
				let thisUrl = location.href;
				let url = encodeURIComponent(thisUrl);
				uni.request({
					url: this.baseURL + '/wxPay/get/JsSignature?url=' + url,
					method: 'GET',
					success: (res) => {
						console.log(res)
						let rData = res.data.data;
						if (res.data.code == 0) {
							//配置微信参数
							wx.config({
								debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
								appId: 'wxfdb3b7e5fb01d447', // 必填，公众号的唯一标识
								timestamp: rData.timestamp, // 必填，生成签名的时间戳
								nonceStr: rData.nonceStr, // 必填，生成签名的随机串
								signature: rData.signature, // 必填，签名
								jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
							});
						} else {
							uni.showToast({
								title: '微信支付配置失败',
								icon: 'error',
								duration: 3000
							})
							return;
						}
					},
					fail: (err) => {
						console.log(err)
						uni.showToast({
							title: '微信支付配置错误',
							icon: 'error',
							duration: 3000
						})
						return;
					}
				})
			}
		},
		onLoad(p) {
			this.is_weixin();
			this.wxConfig(); //微信配置
			if (p.serviceId && p.serviceName && p.serviceDate && p.serviceSite) {
				this.serviceId = p.serviceId
				this.serviceName = p.serviceName
				this.serviceDate = p.serviceDate
				this.serviceSite = p.serviceSite
				this.price = p.price
				this.wxCode = p.code
				uni.removeStorageSync('serviceId');
				uni.removeStorageSync('serviceName');
				uni.removeStorageSync('serviceDate');
				uni.removeStorageSync('serviceSite');
			} else {
				uni.showToast({
					title: '页面数据错误',
					icon: 'error',
					duration: 3000
				})
			}
		}
	}
</script>
<style>
	.tcc {
		background-color: #fff;
		padding: 30px;
		margin: 90px 30px 30px 30px;
		border-radius: 8px;
		text-align: center;

	}
</style>
